package com.study.lihan;
/*
* 主线程捕获子线程异常
* */


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class TestCatchZiException {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> resultList = new ArrayList<Future<String>>();
        // 创建5个线程任务
        for (int i = 0; i < 5; i++) {
            Future<String> future = executorService.submit(new TaskThread(i));
            // 将任务执行结果存储到List中
            resultList.add(future);
        }
        executorService.shutdown();
        // 遍历任务的结果
        for (Future<String> fs : resultList) {
            try {
                System.out.println(Thread.currentThread().getName()+"执行的时间是："+System.currentTimeMillis());
                System.out.println(fs.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}

class  TaskThread implements Callable<String>{
    private int id;
    public TaskThread(int id) {
        this.id = id;
    }
    public String call() {
        if (id == 2 )
            throw new MyException("call()执行过程中抛出异常：" + Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getName()+"执行的时间是："+System.currentTimeMillis());
        //这里模拟具体代码的逻辑
        for (int i = 999999999; i > 0; i--)
            ;
        return "call()方法执行，任务的结果是：" + id + "    " + Thread.currentThread().getName();
    }
}